<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-select v-model="searchObj.projectCode" filterable clearable class="zs-select-md zs-space-right-sm" placeholder="项目名称" @change="queryList">
					<el-option v-for="item in projectList" :key="item.projectCode" :label="item.propertyProjectName" :value="item.projectCode" />
				</el-select>
				<el-date-picker class="zs-space-right-sm" v-model="searchObj.yearMonth" type="month" placeholder="日期" :clearable="true" value-format="YYYY-MM" @change="queryList" />
				<el-select v-model="searchObj.benchmarkType" class="zs-select-md zs-space-right-sm" placeholder="标准对标" :teleported="false" @change="queryList">
					<el-option label="标准对标" value="1" />
					<el-option label="预算对标" value="0" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': searchObj.companyAreaManage || searchObj.standard || searchObj.benchmarkType }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="searchObj.companyAreaManage" class="zs-select-md zs-space-right-sm" placeholder="区域" @change="changeArea">
							<el-option v-for="item in areaList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
						<el-select v-model="searchObj.standard" multiple collapse-tags collapse-tags-tooltip clearable filterable class="zs-select-md zs-space-right-sm" placeholder="标准" @change="queryList" :teleported="false">
							<el-option v-for="item in standList" :key="item.standardNum" :label="item.standardName" :value="item.standardNum" />
						</el-select>
						<el-cascader class="zs-select-md zs-space-right-sm" v-model="city" :options="cityList" placeholder="城市" :props="cascaderProps" clearable filterable @change="changeCity" />
						<el-select v-model="searchObj.specification" class="zs-select-md zs-space-right-sm zs-space-top-sm" placeholder="口径" @change="queryList" :teleported="false">
							<el-option label="管理口径" value="1" />
							<el-option label="EAS口径" value="2" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList"> 查询 </el-button>
			</span>
			<span>
				<el-button class="zs-btn-md fix-width-btn" v-for="item in btnTypeList" :key="item.code" :class="propertyType == item.propertyType ? 'zs-btn-primary' : 'zs-btn-plain'" @click="changePropertyType(item)">{{ item.name }}</el-button>
				<el-button class="zs-btn-plain" @click="exportFn">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
			</span>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column type="index" label="序号" width="60" :align="'center'" :index="(index) => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column label="项目" fixed width="160" align="left">
					<template #default="{ row }">
						<el-tooltip effect="dark" :content="row.projectName || '-'" placement="top">
							<el-link v-if="row.projectName" class="slef-span" type="primary" :underline="false" @click="goDetail(row)">{{ row.projectName }}</el-link>
							<span v-else>-</span>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column prop="standardName" label="标准" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column label="区域" show-overflow-tooltip align="center">
					<template #default="{ row }">
						<span>{{ getDicName('COMPANY_AREA_MANAGE', row.managementArea) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="city" label="城市" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<template v-if="tableData.data.length > 0">
					<template v-for="(item, index) in tableData.data[0].list" :key="index">
						<el-table-column :label="`${item.name}利润率`" v-if="!hideColList.includes(item.name)" align="center">
							<el-table-column :label="searchObj.benchmarkType == 1 ? '标准' : '预算'" width="90" align="center">
								<template #default="{ row }">
									<span>{{ searchObj.benchmarkType == 1 ? row.list[index].standardYuan : row.list[index].budgetYuan }}</span>
								</template>
							</el-table-column>
							<el-table-column label="实际" width="90" align="center">
								<template #default="{ row }">
									<span>{{ row.list[index].actualYuan ? row.list[index].actualYuan : '-' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="对标" width="90" align="center">
								<template #default="{ row }">
									<span :class="{ 'zs-text-red': row.list[index].color == 1, 'zs-text-green': row.list[index].color == 3, 'zs-text-orange': row.list[index].color == 2 }">{{ row.list[index].benchmarking }}</span>
								</template>
							</el-table-column>
						</el-table-column>
					</template>
				</template>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { defaultTableData, getDicName, downloadNewFile } from '@/utils/publicUtils';
	import projectListApi from '@/api/Property/projectList';
	import dbPublicApi from '@/api/dbPublic';
	import manageSum from '@/api/Property/manageSum';
	import { useStore } from 'vuex';
	import { useRouter } from 'vue-router';

	const router = useRouter();
	let store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let searchObj = reactive({ companyAreaManage: '', benchmarkType: '1', pageNo: 1, pageSize: curPageSize.value, yearMonth: '', specification: '1' });

	//城市
	let cityList = ref([]);
	let city = ref([]);
	const cascaderProps = { multiple: false, label: 'name', value: 'code', children: 'childList' };
	const addrBasicsTree = JSON.parse(localStorage.getItem('addrTree') ?? '[]').list;
	cityList.value = addrBasicsTree.map(item => ({
		name: item.name,
		code: item.code,
		childList: item.childList ? item.childList.map(child => ({ name: child.name, code: child.code })) : [],
	}));
	const changeCity = () => {
		searchObj.city = city.value ? city.value[1] : '';
		queryList();
	};

	//右上角按钮类型
	const btnTypeList = ref([
		{ code: 'base', propertyType: 0, name: '基础物业', hideColList: ['商业物业', '外拓物业'] },
		{ code: 'business', propertyType: 1, name: '商业物业', hideColList: ['基础物业', '外拓物业'] },
		{ code: 'extension', propertyType: 2, name: '外拓物业', hideColList: ['基础物业', '商业物业'] },
		{ code: 'company', propertyType: 3, name: '专业公司', hideColList: ['基础物业', '商业物业', '外拓物业'] },
	]);

	//区域
	const areaList = ref([
		{ dictLabel: '整体', dictValue: '' },
		{ dictLabel: '华北', dictValue: 'HUA_BEI' },
		{ dictLabel: '华东', dictValue: 'HUA_DONG' },
		{ dictLabel: '华南', dictValue: 'HUA_NAN' },
		{ dictLabel: '西南', dictValue: 'XI_NAN' },
	]);
	const changeArea = () => {
		searchObj.projectCode = '';
		getProjectList();
		queryList();
	};

	//项目
	let projectList = ref([]);
	const getProjectList = async () => {
		let res = await projectListApi.queryProjectListNoLimitApi({ companyAreaManage: searchObj.companyAreaManage });
		if (res.data.code != 200) return;
		projectList.value = res.data.data;
	};

	//标准
	let standList = ref([]);
	const getStandList = async propertyType => {
		tableData.loading = true;
		let res = await manageSum.standListByPropertyApi({ propertyType: propertyType });
		if (res.data.code != 200) return;
		standList.value = res.data.data || [];
		searchObj.standard = standList.value.map(item => item.standardNum);
	};

	//列表数据源
	const queryList = async () => {
		tableData.loading = true;
		let res = await manageSum.propertyManageSumApi(searchObj);
		if (res.data.code !== 200) return;
		tableData.data = res.data.data.childList;
		tableData.total = res.data.data.totalCount || 0;
		tableData.loading = false;
	};

	//导出
	const exportFn = async () => {
		const fileName = `物业两算一控报表.xls`;
		let fileData;
		let params = {
			...searchObj,
			propertyType: propertyType.value,
		};
		await manageSum.propertyManageSumExportApi(params).then(res => {
			fileData = res.data;
		});
		downloadNewFile(fileData, fileName);
	};

	//切换物业类型
	let hideColList = ref(['商业物业', '外拓物业']);
	let propertyType = ref(0); // 0：基础物业、1：商业物业、2：外拓物业 3: 专业公司
	const changePropertyType = async row => {
		if (row.propertyType != propertyType.value) {
			searchObj.standard = [];
			await getStandList(row.propertyType);
			queryList();
		}
		propertyType.value = row.propertyType;
		hideColList.value = row.hideColList;
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			searchObj.pageSize = size;
		} else {
			searchObj.pageNo = size;
		}
		queryList('init');
	};

	//项目详情
	const goDetail = row => {
		router.push({
			path: '/page/routeController/index',
			query: {
				rid: 'Property/PropertyDashBoardBudgetcAhievement',
				rTitle: '预算对标',
				projectCode: row.projectCode,
				menuKey: '901_wuye_xiangmu',
				pageKey: 'page_903_wuyexiangmu_wuyexiangmu',
				yearmonth: row.yearMonth,
			},
		});
	};

	//更新时间 - 通用
	const queryDataUpdateTime = () => {
		dbPublicApi.queryUpdateTimeApi().then(res => {
			if (res.data.code == 200) {
				searchObj.yearMonth = res.data.data.monthTime;
			}
		});
	};

	const init = () => {
		getProjectList();
		Promise.all([getStandList(0), queryDataUpdateTime()])
			.then(() => {
				queryList();
			})
			.catch(() => {
				tableData.loading = false;
			});
	};

	init();
</script>

<style scoped lang="scss">
	.fix-width-btn {
		width: 80px;
	}
	.slef-span {
		width: 100%;
		:deep(.el-link__inner) {
			text-overflow: -o-ellipsis-lastline;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 1;
			line-clamp: 1;
			-webkit-box-orient: vertical;
			width: 100%;
		}
	}
</style>
